package com.weme.matching.activity

import android.animation.ValueAnimator
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.FragmentActivity
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.osom.proto.message.Brocast
import com.weme.common.R
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.LiveRoomBean
import com.weme.common.base.BaseMvvmActivity
import com.weme.common.network.ERROR_CODE_USER_BALANCE_NOT_ENOUGH
import com.weme.common.network.FEEDBACK_TIPS
import com.weme.common.network.MATCHING_TIPS
import com.weme.common.util.*
import com.weme.matching.databinding.ActivityMatchBinding
import com.weme.matching.view.ViewMatchingSuccess
import com.weme.matching.viewmode.MatchingViewMode
import dev.kratos.api.im_server.v1.MatchCancelReply
import dev.kratos.api.im_server.v1.MatchReply

class MatchingActivity : BaseMvvmActivity<ActivityMatchBinding, MatchingViewMode>() {
    val animator: ValueAnimator = ValueAnimator.ofInt(0, 3)
    var matchId = ""
    var isMatching = false


    private val autoScrollHandler = Handler(Looper.getMainLooper())
    private var currentPage = 0

    var receivedList: ArrayList<String>? = null


    companion object {

        private const val MATCH_BANNER_LIST_KEY = "matchBannerList"
        private const val MATCH_USER_NUM = "matchUseNum"

        fun openActivity(activity: FragmentActivity, matchList: MutableList<String>, matchUseNum: Int) {
            val intent = Intent(activity, MatchingActivity::class.java)
            val options = ActivityOptions.makeCustomAnimation(activity, R.anim.fade_in, R.anim.fade_out) // 将呼叫类型和 UID 或 BEAN 添加到 Intent 中
            intent.putExtra(MATCH_BANNER_LIST_KEY, ArrayList(matchList))
            intent.putExtra(MATCH_USER_NUM, matchUseNum)
            activity.startActivity(intent, options.toBundle())
        }
    }


    private val autoScrollRunnable: Runnable = object : Runnable {
        override fun run() {
            receivedList?.apply {
                if (this.isNotEmpty()) {
                    val imageView = ImageView(this@MatchingActivity)
                    imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                    imageView.loadImage(this[++currentPage % this.size])
                    val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                    imageView.layoutParams = layoutParams
                    imageView.alpha = 0f
                    mBinding.calView.addView(imageView)
                    imageView.fadeIn()

                }

            }
            autoScrollHandler.postDelayed(this, 1000)

        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.calView).init()
        mBinding.tvMatchTips.text = AppMkHelper.decodeString(MATCHING_TIPS)
        mBinding.svgaSearch.playSVGAFromAssets( "search")
        mBinding.tvMoney.text = intent.getIntExtra(MATCH_USER_NUM, 0).toString()
        receivedList = intent.getStringArrayListExtra("matchBannerList")

        receivedList?.apply {
            if (this.isNotEmpty()) {
                val imageView = ImageView(this@MatchingActivity)
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                imageView.loadImage(this[currentPage])
                val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                imageView.layoutParams = layoutParams
                mBinding.calView.addView(imageView)
            }

            autoScrollHandler.postDelayed(autoScrollRunnable, 1000)
        }

        mBinding.imExit.setOnClickListener {
            if (isMatching) {
                viewModel.setMatchCancel(matchId)
            }
            finish()
        }


     LiveEventBus.get<Any>(LiveConfig.NET_WORK_MATCHING).observe(this) {
            if (it is MatchCancelReply) {
                finish()
            } else if (it is MatchReply) {

                matchId = it.matchId
                isMatching = true

                //     CallActivity.openActivity(requireActivity(), CallOperationType.INCOMING_MATCH,"")


            } else if (it == ERROR_CODE_USER_BALANCE_NOT_ENOUGH) {
                showToast("跳转到金币商城")
                finish()
            }
        }



     LiveEventBus.get<Any>(Brocast.BrocastId.CMD_MATCH_ANSWER.name).observe(this) {
            if (it is Brocast.MatchMessage) {
                isMatching = false //如果是虚拟主播 需要3秒延迟 现在服务端我看着有延迟 先不管
                if (it.user.isVirtual == 1) {
                    showToast("匹配到虚拟主播 等待三秒")
                    mBinding.calView.postDelayed({
                        onMatchSuccess(it)
                    }, 3000)

                } else {
                    onMatchSuccess(it)
                }
            }
        }



     LiveEventBus.get<Any>(Brocast.BrocastId.CMD_MATCH_TIMEOUT.name).observe(this) {
            isMatching = false
            if (matchNum >= 2) {
                showToast(getString(com.example.resources.R.string.match_time_out))
                finish()
            } else if (it is Brocast.MatchMessage) {
                val binding = ViewMatchingSuccess(this@MatchingActivity)
                mBinding.root.addView(binding)
                binding.initView(it)
                mBinding.root.postDelayed({
                    binding.getTvContent().text = getString(com.example.resources.R.string.match_time_host)
                    mBinding.root.postDelayed({
                        binding.onDestroy()
                        mBinding.root.removeView(binding)
                        viewModel.getMatchint()
                        isMatching = true
                        matchNum += 1
                    }, 1000)
                }, 2000) //                val dialog = CustomDialogFragment.newInstance(title = "", content = getString(com.example.resources.R.string.match_matching), positiveButtonText = getString(com.example.resources.R.string.cancel), negativeButtonText = getString(com.example.resources.R.string.yes), isDismiss = false, listener = object : CustomDialogFragment.DialogClickListener {
                //                    override fun onPositiveButtonClick() {
                //                        finish()
                //                    }
                //
                //                    override fun onNegativeButtonClick() {
                //                        viewModel.getMatchint()
                //                        isMatching = true
                //                        matchNum += 1
                //
                //
                //                    }
                //                })
                //                dialog.show(supportFragmentManager, "CustomDialog")
            }

        }
    }

    fun onMatchSuccess(it: Brocast.MatchMessage) { //展示主播信息
        val binding = ViewMatchingSuccess(this@MatchingActivity)
        mBinding.root.addView(binding)
        binding.initView(it)
        mBinding.root.postDelayed({
            binding.onDestroy()
            ARouterHelper.navigateToLiveRoomActivity(this, LiveRoomBean(rtcToken = it.user.rtcToken, userId = it.matchedUser.uid, chatRoomId = it.chatRoomId, channelName = it.channelName, channelId = it.channelId, matchMessage = it, isIncoming = false))
            finish()
        }, 500)


        animator.pause()

        mBinding.svgaSearch.pauseAnimation()
    }

    override fun onResume() {
        super.onResume()
        if (!isMatching) {
            viewModel.getMatch()

            animator.repeatCount = ValueAnimator.INFINITE
            animator.duration = 1000
            animator.addUpdateListener { valueAnimator ->
                val numberOfDots = valueAnimator.animatedValue as Int
                val text = "Loading" + ".".repeat(numberOfDots)
                mBinding.tvSelect.text = text
            }
            mBinding.svgaSearch.startAnimation()


            // 启动动画
            animator.start()
        }
    }

    override fun onStart() {
        super.onStart()
        mBinding.svgaSearch.startAnimation()

    }

    override fun onStop() {
        super.onStop()
        mBinding.svgaSearch.pauseAnimation()
    }

    var matchNum = 0

    override fun getViewModelClass(): Class<MatchingViewMode> = MatchingViewMode::class.java
    override fun onBackPressed() {
        if (isMatching) {
            viewModel.setMatchCancel(matchId)
        }
        finish()
    }

    override fun onPause() {
        super.onPause() // 在 onPause 中停止自动翻页
        autoScrollHandler.removeCallbacks(autoScrollRunnable)
    }

    override fun onDestroy() {

        super.onDestroy()
        mBinding.svgaSearch.clear()
        animator.pause()
        animator.reverse()

    }

}